/*
 * barrier.hpp
 *
 *  Created on: 04.04.2011
 *      Author: inkooboo
 */

#ifndef _MISC_BARRIER_HPP_
# define _MISC_BARRIER_HPP_

# include <boost/thread/mutex.hpp>

class barrier_t
{
public:
    barrier_t(size_t count) :
        counter_(count)
    {
        waiter_.lock();
    }

    void release_one()
    {
        boost::mutex::scoped_lock g(guard_);

        --counter_;

        assert((counter_ >= 0));

        if (0 == counter_)
        {
            drop_waitings();
        }
    }

    void wait()
    {
        if (counter_ <= 0)
        {
            return;
        }

        waiter_.lock();
        waiter_.unlock();
    }

private:
    void drop_waitings()
    {
        waiter_.unlock();
    }

    int counter_;
    boost::mutex guard_;
    boost::mutex waiter_;
};

#endif /* _MISC_BARRIER_HPP_ */
